﻿using FswPdf.Models;
using iText.Forms;
using iText.Kernel.Pdf;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace FswPdf.Controllers
{
    /// <summary>
    /// 表单填充
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class FillFormsController : ControllerBase
    {
        private readonly ILogger _logger;
        public FillFormsController(ILogger<FillFormsController> logger)
        {
            _logger = logger;
        }
        [HttpGet]
        public async Task<Msg> GetTemplate(string id)
        {
            var template = Helpers.PdfTemplates?.FirstOrDefault(p => p.Id == id);
            if (template == null)
            {
                return new Msg
                {
                    success = false,
                };
            }
            using var pdf = new PdfDocument(new PdfReader(Path.Combine(Helpers.TemplateDirectory, template.Path)));
            var form = PdfAcroForm.GetAcroForm(pdf, true);
            // 获取所有字段名
            var fields = form.GetAllFormFields();

            Dictionary<string, string?> dics = [];
            foreach (var item in fields)
            {
                dics.TryAdd(item.Key,item.Value.GetValueAsString());
            }
            return new Msg
            {
                data = dics,
            };
        }
        [HttpPost]
        public async Task<Msg> Post(FillContent value)
        {
            var template = Helpers.PdfTemplates?.FirstOrDefault(p=>p.Id==value.TemplateId);
            if (template == null)
            {
                return new Msg
                {
                    success=false,
                    msg="模板未找到"
                };
            }
            var folderName = $"{DateTime.UtcNow.ToString("yyyy-MM-dd_HH-mm-ss")}_{Guid.NewGuid()}";
            var fillDirectory = Path.Combine(Helpers.PdfFillDirectory,folderName);
            Directory.CreateDirectory(fillDirectory);

            var filePath = Path.Combine(fillDirectory, $"{template.Name ?? template.Id}.pdf");

           using var pdf = new PdfDocument(new PdfReader(Path.Combine(Helpers.TemplateDirectory, template.Path)),
                new PdfWriter(new FileStream(filePath, FileMode.Create)));

            var form = PdfAcroForm.GetAcroForm(pdf, true);

            foreach (var item in value.Texts)
            {
                if (item.Value == null)
                    continue;
                var field=form.GetField(item.Name);
                field.SetValue(item.Value);
            }
            foreach (var item in value.checkBoxes)
            {
                if (item.Value == null)
                    continue;
                if (item.Value==true)
                {
                    var field = form.GetField(item.Name);
                    field.SetCheckType(item.Type);
                    field.SetValue("on");
                }
            }
            pdf.Close();
            return new Msg
            {
                success=true,
                data= Path.GetFullPath(filePath)
            };
        }
    }
}
